﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml;
using EpiInfoCloudMagpiBridge.Models;
using Ewav.Security;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace EpiInfoCloudMagpiBridge.Controllers
{
    public static class HelperFunctions
    {

        const string _baseAddressMagpiServer_SurveyList = "https://www.magpi.com/api/surveys/";


        public static XmlDocument getMagpiXml(string url)
        {
            // Set up Uri     
            UriBuilder ewavAzureUriBuilder = new UriBuilder(url);

            // Set up Http Request      
            var http = (HttpWebRequest)WebRequest.Create(ewavAzureUriBuilder.Uri);
            http.Accept = "application/xml";
            http.ContentType = "application/xml";
            http.Method = "GET";

            // Get response     
            var response = http.GetResponse();

            // Read response  
            var stream = response.GetResponseStream();
            var sr = new StreamReader(stream);
            var content = sr.ReadToEnd();

            XmlDocument xDoc = new XmlDocument();

            xDoc.LoadXml(content);

            return xDoc;
        }


        public static List<MagpiAzureMapping> getAllMagpiSurveys()
        {
            Cryptography cy = new Cryptography();

            //  Get magpiUsername    
            MagpiEWAVEntities context = new MagpiEWAVEntities(cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));
            List<MagpiAccountSetting> magpiAccountSettingList = context.MagpiAccountSettings.Where(
                z => z.EWAVUserID == ApplicationModel.CurrentEwavUserId).ToList();
            var magpiUsername = magpiAccountSettingList[0].MagpiUsername;
            var magpiAccesstoken = magpiAccountSettingList[0].MagpiAccessToken;


            var magpiUriBuilder = new UriBuilder(_baseAddressMagpiServer_SurveyList); var query = HttpUtility.ParseQueryString("");
            query["username"] = magpiUsername;
            query["accesstoken"] = magpiAccesstoken;
            magpiUriBuilder.Query = query.ToString();

            // Retrieve XML from MagPi service  
            XmlDocument xDoc = getMagpiXml(magpiUriBuilder.Uri.ToString());

            // Convert Xml to Json    
            string json = JsonConvert.SerializeXmlNode(xDoc);

            JObject outer = JObject.Parse(json);
            JObject children = outer["Surveys"] as JObject;

            List<MagpiAzureMapping> MagpiAzureMappingList = new List<MagpiAzureMapping>();

            if (children != null)
            {
                JArray children2 = children["Survey"] as JArray;


                if (children2 != null)
                {
                    foreach (var jToken in children2)
                    {
                        var jObject = (JObject)jToken;
                        MagpiAzureMapping m = new MagpiAzureMapping()
                        {
                            SurveyID = jObject["SurveyId"].ToString(),
                            SurveyName = jObject["SurveyName"].ToString(),
                            Owner = jObject["Owner"].ToString()
                        };

                        MagpiAzureMappingList.Add(m);

                    }
                }

            }

            return MagpiAzureMappingList;
        }

        public static bool UserHasAzureServices()
        {
            Cryptography cy = new Cryptography();
            MagpiEWAVEntities context =
                new MagpiEWAVEntities(cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));

            return context.AzureMobileServiceSettings.Where(
                    z => z.EWAVUserID == ApplicationModel.CurrentEwavUserId).ToList().Any();    
        }

        public static bool UserHasMagpiServices()
        {
            Cryptography cy = new Cryptography();
            MagpiEWAVEntities context =
                new MagpiEWAVEntities(cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));

            return context.MagpiAccountSettings.Where(
                    z => z.EWAVUserID == ApplicationModel.CurrentEwavUserId).ToList().Any();
        }
    }
}